<template>
    <div class="cut">
        <nya-container title="水印移除">
            <div class="form-row">
                <div class="col-12">
                    <div class="custom-file">
                        <input
                            ref="input"
                            type="file"
                            name="image"
                            class="form-control"
                            accept="image/*"
                            @change="setImage"
                        />
                    </div>
                </div>
                <div class="col-12" style="margin-top: 1em">
                    <div class="input-group ">
                        模式选择 | &nbsp;
                        <div class="radio-group">
                            <nya-radio-group v-model="index">
                                <nya-radio v-for="(label, i) in labels" class="mr-15" :value="i" :key="i"
                                           :label="label.label"/>
                            </nya-radio-group>
                        </div>

                    </div>
                    <small> {{ labels[index].desc }} </small>

                    <div class="col-12 top-margin-1em">
                        <div class="form-inline" v-show="index === 2">
                            <span class="col-form-label">输入填充水印颜色</span>
                            <input class="form-control" type="text" v-model="fillColor">
                        </div>
                    </div>
                </div>

                <div class="col-12 top-margin-1em">
                    <!--                    <nya-input-->
                    <!--                        style="width: 80%"-->
                    <!--                        v-model.trim="imgUrl"-->
                    <!--                        label="输入水印图网络地址"-->
                    <!--                        placeholder="图片rul"-->
                    <!--                        autocomplete="off"-->
                    <!--                        type="text"-->
                    <!--                        @keyup.enter="url2base64"-->
                    <!--                    />-->
                    <!--                    <button type="button" class="nya-btn" @click="url2base64">-->
                    <!--                        获取图片-->
                    <!--                    </button>-->
                </div>


            </div>

            <div class="form-group top-margin-1em">
                <button class="btn btn-outline-primary" @click="reset">重置</button>
                <button class="btn btn-outline-danger col-2" @click="removeWater">执行</button>
            </div>

            <div class="content top-padding-1em">
                <section class="cropper-area">
                    <div class="img-cropper">
                        <client-only>
                            <vue-cropper
                                ref="cropper"
                                :src="imgSrc"
                                @zoom="reset"
                                @ready="cropMove"
                                @cropmove="cropMove"
                                preview=".preview"
                            />
                        </client-only>
                        <small>
                            原图宽 = {{ this.maxW }} 高 = {{ this.maxH }} <br/>
                            水印款 = {{ this.width }} 高 = {{ this.height }} <br/>
                            水印 x = {{ this.x }} y == {{ this.y }} <br/>
                        </small>
                    </div>
                </section>
                <section class="preview-area">
                    <p>水印区预览</p>
                    <div class="preview"/>
                </section>
            </div>
        </nya-container>

        <nya-container title="返回结果">
            <div class="cropped-image">
                <img
                    v-if="cropImg"
                    :src="cropImg"
                    alt="去水印结果"
                />
                <div v-else class="crop-placeholder"/>
            </div>
        </nya-container>

        <nya-container title="Tips" icon="bulb-outline">
            <li>去水印功能非前段实现，服务器承受能力有限，请谨慎使用</li>
            <li>去水印功能由<a href="https://github.com/liuyueyi/quick-media" target="_blank">quick-media</a>实现，请右键保存处理后的图片
            </li>
            <li>如果生成时间过长或生成失败，请使用其他浏览器，推荐使用 Chrome</li>
        </nya-container>
    </div>
</template>

<script>
// Local
import VueCropper from 'vue-cropperjs';
import 'cropperjs/dist/cropper.css';

export default {
    name: 'ImageCut',
    head() {
        return this.$store.state.currentTool.head;
    },
    components: {
        VueCropper,
    },
    data() {
        return {
            index: 0,
            labels: [
                {"label": '像素化', desc: '将水印部分马赛克化，从而实现去水印效果'},
                {"label": '背景色填充', desc: '最大努力使用图片背景颜色填充水印部分'},
                {"label": '指定色填充', desc: '使用指定的颜色填充水印部分'},
            ],
            n: null,
            imgSrc: "",
            cropImg: '',
            data: null,
            width: 960,
            height: 320,
            x: 0,
            y: 0,
            maxW: 0,
            maxH: 0,
            imgUrl: '',
            pixelSize: 10,
            fillColor: "#FFFFFF"
        };
    },
    methods: {
        init() {
            this.data = this.$refs.cropper.getData();
            this.imgData = this.$refs.cropper.getImageData();
            this.maxW = this.imgData.naturalWidth;
            this.maxH = this.imgData.naturalHeight;
            this.width = parseInt(this.data.width);
            this.height = parseInt(this.data.height);
            this.x = parseInt(this.data.x);
            this.y = parseInt(this.data.y);
        },
        cropMove() {
            this.init();
        },
        url2base64() {
            try {
                this.imgSrc = this.imgUrl;
                const img = this.imgUrl;
                const canvas = document.createElement("canvas");
                canvas.width = img.width;
                canvas.height = img.height;
                const ctx = canvas.getContext("2d");
                ctx.drawImage(img, 0, 0, img.width, img.height);
                const ext = img.src.substring(img.src.lastIndexOf(".") + 1).toLowerCase();
                this.imgSrc = canvas.toDataURL("image/" + ext);
            } catch (e) {
                console.log(e);
            }
        },
        removeWater() {
            let color = this.fillColor.trim();
            if (color.startsWith("#")) {
                color = color.substring(1);
            }
            if (color.length === 3) {
                color = "0xFF" + color[0] + color[0] + color[1] + color[1] + color[2] + color[2];
            } else if (color.length === 6) {
                color = "0xFF" + color;
            } else {
                this.color = "填充颜色非法";
                return;
            }
            let type;
            if (this.index === 0) {
                type = "pixel";
            } else if (this.index === 1) {
                type = "bg";
            } else {
                type = "fill";
            }

            let index = this.imgSrc.indexOf(";base64,");
            let data = this.imgSrc.substring(index + ";base64,".length);

            this.$axios
                .post('https://story.hhui.top/media/water/remove?appKey=tool', {
                    "offsetX": this.x,
                    "offsetY": this.y,
                    "waterMarkW": this.width,
                    "waterMarkH": this.height,
                    "imgUrl": data,
                    "pixelSize": this.pixelSize,
                    "fillColor": color,
                    "type": type,
                })
                .then(e => {
                    let result = e.data;
                    if (result.status.code === 200) {
                        result = result.result;
                        this.cropImg = result.base64;
                    }
                })
                .catch(err => {
                    this.$swal({
                        type: 'error',
                        title: '计数失败',
                        text: `ERROR: 获取数据失败，请刷新页面重试 ${err}`
                    });
                });
        },
        reset() {
            this.$refs.cropper.reset();
            this.init();
        },
        setImage(e) {
            const file = e.target.files[0];
            if (file.type.indexOf('image/') === -1) {
                this.$noty.success('请选择需要编辑的图片', {timeout: 500});
                return;
            }
            if (typeof FileReader === 'function') {
                const reader = new FileReader();
                reader.onload = (event) => {
                    this.imgSrc = event.target.result;
                    this.$refs.cropper.replace(event.target.result);
                    this.init();
                };
                reader.readAsDataURL(file);
            } else {
                this.$noty.error('文件阅读API权限未开哦~', {timeout: 500});
            }
        },
    }
};
</script>

<style lang="scss">

.cut {
    .form-group {
        input {
            border: 1px solid #ced4da;
        }
    }
}


.content {
    display: flex;
    justify-content: space-between;
}

.cropper-area {
    width: 614px;
}

.preview-area {
    width: 307px;
    margin-top: -3rem;
}

.preview-area p {
    font-size: 1.25rem;
    margin: 0;
    margin-bottom: 1rem;
}

.preview-area p:last-of-type {
    margin-top: 1rem;
}

.preview {
    width: 100%;
    height: calc(372px * (9 / 16));
    overflow: hidden;
}

.crop-placeholder {
    width: 100%;
    height: 200px;
    background: #ccc;
}

.cropped-image img {
    max-width: 100%;
}
</style>
